<script setup lang="ts">
import { NButton, NMessageProvider } from 'naive-ui';
import CryptoJS from 'crypto-js';
import { ref, unref } from 'vue';
import { useMessage } from 'naive-ui';

const message = useMessage();
console.log('Message instance:', message);
if (!message) {
    console.error('Message provider not found in context');
}

// 读取环境变量
const {
    VITE_GLOBAL_SPARK_AI_APPID,
    VITE_GLOBAL_SPARK_AI_APISECRET,
    VITE_GLOBAL_SPARK_AI_APIKEY,
} = import.meta.env;

console.log('Env vars:', {
    VITE_GLOBAL_SPARK_AI_APPID,
    VITE_GLOBAL_SPARK_AI_APISECRET,
    VITE_GLOBAL_SPARK_AI_APIKEY,
});

if (!VITE_GLOBAL_SPARK_AI_APPID || !VITE_GLOBAL_SPARK_AI_APISECRET || !VITE_GLOBAL_SPARK_AI_APIKEY) {
    console.error('Environment variables are not properly configured');
    message.error('环境变量未正确配置，请检查 .env 文件');
    throw new Error('Environment variables are missing');
}

const getWebsocketUrl = () => {
    if (!VITE_GLOBAL_SPARK_AI_APISECRET || !VITE_GLOBAL_SPARK_AI_APIKEY) {
        console.error('API secret or key is missing');
        message.error('API 密钥缺失，请检查 .env 文件');
        return '';
    }
    let url = 'wss://spark-api.xf-yun.com/v1/x1';
    const host = 'spark-api.xf-yun.com';
    const apiKeyName = 'api_key';
    const date = new Date().toGMTString();
    const algorithm = 'hmac-sha256';
    const headers = 'host date request-line';
    let signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1/x1 HTTP/1.1`;
    let signatureSha = CryptoJS.HmacSHA256(signatureOrigin, VITE_GLOBAL_SPARK_AI_APISECRET);
    let signature = CryptoJS.enc.Base64.stringify(signatureSha);
    let authorizationOrigin = `${apiKeyName}="${VITE_GLOBAL_SPARK_AI_APIKEY}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
    let authorization = btoa(authorizationOrigin);
    const fullUrl = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;
    console.log('Generated URL:', fullUrl);
    return fullUrl;
};

const url = ref(getWebsocketUrl());
const isLoading = ref(false);
const sMsg = ref('');
const chartContentRef = ref<HTMLDivElement>();

if (!url.value) {
    message.error('WebSocket URL 未生成，请检查环境变量');
}

const sendMsg = () => {
    if (!message) {
        console.error('Message hook unavailable, skipping sendMsg');
        return;
    }
    if (unref(isLoading)) {
        message.warning('加载中...');
        return;
    }
    if (!unref(sMsg)) {
        message.warning('请输入内容');
        return;
    }
    if (!chartContentRef.value) {
        console.error('chartContentRef is not bound to DOM');
        return;
    }
    if (!url.value) {
        message.error('WebSocket URL 未生成，请检查环境变量');
        return;
    }

    const userMsg = document.createElement('div');
    userMsg.classList.add('msg-user');
    const userMsgMain = document.createElement('div');
    userMsgMain.innerHTML = unref(sMsg);
    userMsg.appendChild(userMsgMain);
    chartContentRef.value.appendChild(userMsg);

    const resMsg = document.createElement('div');
    resMsg.classList.add('msg-ai');
    const resMsgMain = document.createElement('div');
    resMsg.appendChild(resMsgMain);
    chartContentRef.value.appendChild(resMsg);

    const socket = new WebSocket(url.value);
    socket.addEventListener('open', (e) => {
        isLoading.value = true;
        const params = {
            header: {
                app_id: VITE_GLOBAL_SPARK_AI_APPID,
                uid: '星火网页测试',
            },
            parameter: {
                chat: {
                    domain: 'x1',
                    temperature: 0.5,
                    max_tokens: 1024,
                },
            },
            payload: {
                message: {
                    text: [
                        { role: 'user', content: unref(sMsg) },
                    ],
                },
            },
        };
        console.log('Sending params:', params);
        socket.send(JSON.stringify(params));
    });

    let resMsgText = '';
    socket.addEventListener('message', ({ data }) => {
        isLoading.value = false;
        try {
            const response = JSON.parse(data);
            console.log('Raw WebSocket Response:', response); // 调试原始响应
            if (response.header && response.header.code !== 0) {
                console.error('API Error:', response.header.message);
                message.error(`API 错误: ${response.header.message}`);
                return;
            }
            if (response.payload && response.payload.choices && Array.isArray(response.payload.choices.text)) {
                const content = response.payload.choices.text[0].content;
                if (content !== undefined && content !== null && content !== '') { // 过滤无效值
                    resMsgText += content;
                    resMsgMain.innerHTML = resMsgText;
                } else {
                    console.log('Skipping undefined or empty content:', content);
                }
            } else {
                console.log('Invalid response format, skipping:', response);
            }
        } catch (e) {
            console.error('Error parsing WebSocket message:', e);
            message.error('消息解析失败');
        }
    });

    socket.addEventListener('error', (e) => {
        isLoading.value = false;
        console.error('WebSocket error:', e);
        message.error('连接失败，请检查网络或API密钥');
    });

    socket.addEventListener('close', (event) => {
        isLoading.value = false;
        console.log('WebSocket closed:', event.code, event.reason);
        message.error(`连接关闭，代码: ${event.code}, 原因: ${event.reason}`);
    });
};
</script>

<template>
    <div class="container">
        <div class="chat-content" ref="chartContentRef"></div>
        <div class="ask-content">
            <textarea v-model="sMsg"></textarea>
            <div class="opt">
                <n-button type="primary" size="large" @click="sendMsg">发送</n-button>
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
.container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f2f2f2;

    .chat-content {
        flex: 1;
        overflow-y: scroll;
        height: 10%0;

        .msg-ai {
            background: white;
            text-align: left;
        }

        .msg-user {
            margin-bottom: 10px;
            text-align: right;
        }
    }

    .ask-content {
        height: 150px;
        background: white;
        border: 1px solid #eee;
        padding: 8px;
        position: relative;

        textarea {
            border: none;
            width: 100%;
            height: 100%;
            padding: 10px;
            background: #f2f2f2;
            outline: none;
        }

        .opt {
            text-align: right;
            position: absolute;
            inset: auto 10px 10px auto;
        }
    }
}
</style>